package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class TsLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object  doConcurrentOperation(ProceedingJoinPoint point, TsLogin tsLogin){
        RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) previousAttributes;
        //获取请求对象
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        //必须登录
        if (tsLogin.required()){
            //没有登录
            if (StringUtils.isEmpty(token)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }else {
                //从缓存中获取用户信息
                String loginKey= RedisConstant.USER_LOGIN_KEY_PREFIX+token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                if (userInfo==null){
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
            }
        }
        //登录
        try {
            if (!StringUtils.isEmpty(token)){
                //从缓存中获取数据
                String loginKey=RedisConstant.USER_LOGIN_KEY_PREFIX+token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                if (userInfo!=null){
                    //将用户id存储到当前线程
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }
            return point.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            AuthContextHolder.removeUserId();
        }
    }
}
